package fm.huanxin.task;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import fm.dao.MongoBaseDao;
import fm.huanxin.api.MessageApi;
import fm.mongo.MCondition;
import fm.mongo.MRel;
import fm.mongo.MongoTable;
import fm.util.DateUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * Created by CM on 2017/7/12.
 */
@Component
public class ChatMessageSchedule {
    private static final Logger LOGGER = LoggerFactory.getLogger(ChatMessageSchedule.class);
    @Autowired
    MongoBaseDao mongoBaseDao;

    /**
     * 发送规划的信息
     * 每分钟发送13条
     */
    public void sendMsgSchedule() {
        MCondition mc = MCondition.create(MRel.and);
        mc.append(MCondition.create(MRel.gte).append("create_time", DateUtils.getDayStart(new Date())));
        mc.append("status", 0);

        try {
            List<DBObject> msgs = (List<DBObject>) mongoBaseDao.getPageList(mc.toDBObject().toMap(), DBObject.class,
                    25, 1, MongoTable.huanxin_message);
            if (CollectionUtils.isNotEmpty(msgs)) {
                for (DBObject msg : msgs) {
                    try {
                        MessageApi.sendMessage((String) msg.get("message"), (String) msg.get("to"), (String) msg.get("from"));
                        DBObject query = new BasicDBObject("_id", msg.get("_id"));
                        mongoBaseDao.updateOne(query.toMap(), new BasicDBObject("status", 1), MongoTable.huanxin_message);
                        LOGGER.info("换新消息推送成功:{}to{}:" + msg.get("message"), msg.get("from"), msg.get("to"));
                    } catch (Exception ex) {
                        LOGGER.error("环信消息发送失败", ex);
                        DBObject query = new BasicDBObject("_id", msg.get("_id"));
                        mongoBaseDao.updateOne(query.toMap(), new BasicDBObject("status", 2).append("err_msg", ex.getMessage()),
                                MongoTable.huanxin_message);
                        continue;
                    }
                }
            }

        } catch (Exception e) {
            LOGGER.error("环信消息推送任务启动失败:", e);
        }
    }
}
